package com.tnovoselec.android.mojevijesti.parser;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.os.SystemClock;
import android.util.Log;

import com.tnovoselec.android.mojevijesti.dto.ChannelDto;

public class ChannelParser extends DefaultHandler {

	private static final String TAG_CHANNEL = "channel";
	private static final String TAG_ITEM = "item";

	private static final String ATTR_NAME = "name";
	private static final String ATTR_URL = "url";
	private static final String ATTR_ICON = "icon";

	private boolean inChannel = false;
	private boolean inItem = false;

	private List<ChannelDto> channels = new ArrayList<ChannelDto>();

	private ChannelDto item;

	private StringBuilder buffer;

	private long parsingStartTime;

	@Override
	public void startDocument() throws SAXException {
		parsingStartTime = SystemClock.elapsedRealtime();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		buffer = new StringBuilder("");

		if (localName.equalsIgnoreCase(TAG_CHANNEL)) {
			inChannel = true;
			item = new ChannelDto();
			if (attributes.getIndex(ATTR_NAME) != -1) {
				item.setChannelName(attributes.getValue(ATTR_NAME));
			}
			if (attributes.getIndex(ATTR_ICON) != -1) {
				item.setIconUrl(attributes.getValue(ATTR_ICON));
			}
		} else if (localName.equalsIgnoreCase(TAG_ITEM)) {
			inItem = true;
			String name = null;
			String url = null;
			if (attributes.getIndex(ATTR_NAME) != -1) {
				name = attributes.getValue(ATTR_NAME);
			}
			if (attributes.getIndex(ATTR_URL) != -1) {
				url = attributes.getValue(ATTR_URL);
			}
			if (name != null && url != null) {
				item.put(name, url);
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (localName.equalsIgnoreCase(TAG_CHANNEL)) {
			inItem = false;
			channels.add(item);
		} else if (localName.equalsIgnoreCase(TAG_ITEM)) {
			inChannel = false;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		buffer.append(String.valueOf(ch, start, length));
	}

	@Override
	public void endDocument() throws SAXException {
		Log.i(getClass().getName(), "XML parsing took " + (SystemClock.elapsedRealtime() - parsingStartTime) / 1000f + " sec");
		Log.i(getClass().getName(), "Have " + channels.size() + " channels");
	}

	public List<ChannelDto> getChannels() {
		return channels;
	}
}
